<template>
  <div class="order-management">
    <h1>订单管理</h1>
    
    <!-- 查询区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" @submit.prevent="searchOrders" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="客户名称">
              <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="订单状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
                <el-option label="待排产" value="待排产" />
                <el-option label="已排产" value="已排产" />
                <el-option label="生产中" value="生产中" />
                <el-option label="生产完成" value="生产完成" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开始日期">
              <el-date-picker
                v-model="searchForm.startDate"
                type="date"
                placeholder="选择开始日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="结束日期">
              <el-date-picker
                v-model="searchForm.endDate"
                type="date"
                placeholder="选择结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: right;">
            <el-button type="primary" @click="searchOrders" :loading="loading">查询</el-button>
            <el-button @click="resetSearch">重置</el-button>
            <el-button type="success" @click="addOrder">新增订单</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 订单列表 -->
    <el-card class="table-card">
      <el-table :data="orders" v-loading="loading" border stripe style="width: 100%">
        <el-table-column prop="orderId" label="订单ID" width="150" show-overflow-tooltip sortable />
        <el-table-column prop="customerName" label="客户名称" width="150" show-overflow-tooltip sortable />
        <el-table-column prop="customerContact" label="客户联系方式" width="150" show-overflow-tooltip sortable />
        <el-table-column prop="dueDate" label="交货日期" width="120" sortable />
        <el-table-column prop="status" label="订单状态" width="100" sortable>
          <template #default="scope">
            <el-tag :type="getOrderStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
      </template>
        </el-table-column>
        <el-table-column prop="totalQuantity" label="总数量" width="100" sortable />
        <el-table-column prop="completedQuantity" label="已完成数量" width="120" sortable />
        <el-table-column prop="completionRate" label="完成率" width="100" sortable>
          <template #default="scope">
            {{ (scope.row.completionRate * 100).toFixed(1) }}%
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" sortable />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="viewOrder(scope.row)">详情</el-button>
            <el-button size="small" @click="editOrder(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              type="warning" 
              @click="updateOrderStatus(scope.row)"
              :disabled="scope.row.status === '生产完成'"
            >
              状态
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="deleteOrder(scope.row)"
              :disabled="scope.row.status === '生产中' || scope.row.status === '生产完成'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageNum"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, prev, pager, next, jumper" background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          style="margin-top: 20px; text-align: right"
        />
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog v-model="showDetailDialog" :title="`订单详情 - ${currentOrder?.orderId}`" width="80%">
      <div v-if="currentOrder">
        <!-- 基本信息 -->
        <el-descriptions :column="3" border style="margin-bottom: 20px;">
          <el-descriptions-item label="订单ID">{{ currentOrder.orderId }}</el-descriptions-item>
          <el-descriptions-item label="客户ID">{{ currentOrder.customerId }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ currentOrder.customerName }}</el-descriptions-item>
          <el-descriptions-item label="客户联系方式">{{ currentOrder.customerContact }}</el-descriptions-item>
          <el-descriptions-item label="交货日期">{{ currentOrder.dueDate }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusTagType(currentOrder.status)">{{ currentOrder.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="总数量">{{ currentOrder.totalQuantity }}</el-descriptions-item>
          <el-descriptions-item label="已完成数量">{{ currentOrder.completedQuantity }}</el-descriptions-item>
          <el-descriptions-item label="完成率">{{ (currentOrder.completionRate * 100).toFixed(1) }}%</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentOrder.createTime }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ currentOrder.updateTime }}</el-descriptions-item>
        </el-descriptions>

        <!-- 订单项列表 -->
        <h3>订单项明细</h3>
        <el-table :data="currentOrder.orderItems" border style="margin-top: 10px;">
          <el-table-column prop="orderItemId" label="订单项ID" width="150" sortable />
          <el-table-column prop="productId" label="产品ID" width="120" sortable />
          <el-table-column prop="productName" label="产品名称" width="150" sortable />
          <el-table-column prop="productDescription" label="产品描述" min-width="200" show-overflow-tooltip sortable />
          <el-table-column prop="quantity" label="数量" width="80" sortable />
          <el-table-column prop="priority" label="优先级" width="100" sortable>
            <template #default="scope">
              <el-tag :type="getPriorityTagType(scope.row.priority)">
                {{ getPriorityLabel(scope.row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="producedQuantity" label="已生产数量" width="120" sortable />
          <el-table-column prop="status" label="状态" width="100" sortable>
            <template #default="scope">
              <el-tag :type="getItemStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="completionRate" label="完成率" width="100" sortable>
            <template #default="scope">
              {{ (scope.row.completionRate * 100).toFixed(1) }}%
            </template>
          </el-table-column>
        </el-table>
      </div>
      
      <template #footer>
        <el-button @click="showDetailDialog = false">关闭</el-button>
        <el-button type="primary" @click="refreshOrderProgress" :loading="refreshingProgress">
          刷新进度
        </el-button>
      </template>
    </el-dialog>

    <!-- 新增/编辑订单对话框 -->
    <el-dialog v-model="showFormDialog" :title="formTitle" width="70%">
      <el-form ref="orderFormRef" :model="orderForm" :rules="orderRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="客户ID" prop="customerId">
              <el-input v-model="orderForm.customerId" placeholder="请输入客户ID" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户名称" prop="customerName">
              <el-input v-model="orderForm.customerName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="客户联系方式" prop="customerContact">
              <el-input v-model="orderForm.customerContact" placeholder="请输入客户联系方式" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="交货日期" prop="dueDate">
          <el-date-picker
            v-model="orderForm.dueDate"
            type="date"
            placeholder="选择交货日期"
            value-format="YYYY-MM-DD"
            style="width: 200px;"
          />
        </el-form-item>

        <!-- 订单项列表 -->
        <el-form-item label="订单项" required>
          <div style="width: 100%;">
            <el-button type="primary" @click="addOrderItem" style="margin-bottom: 10px;">
              添加订单项
            </el-button>
            <el-table :data="orderForm.orderItems" border>
              <el-table-column label="产品ID" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.productId" placeholder="产品ID" />
                </template>
              </el-table-column>
              <el-table-column label="产品名称" width="150">
                <template #default="scope">
                  <el-input v-model="scope.row.productName" placeholder="产品名称" />
                </template>
              </el-table-column>
              <el-table-column label="产品描述" min-width="200">
                <template #default="scope">
                  <el-input v-model="scope.row.productDescription" placeholder="产品描述" />
                </template>
              </el-table-column>
              <el-table-column label="数量" width="100">
            <template #default="scope">
                  <el-input-number v-model="scope.row.quantity" :min="1" style="width: 100%;" />
            </template>
          </el-table-column>
              <el-table-column label="优先级" width="100">
            <template #default="scope">
                  <el-select v-model="scope.row.priority" style="width: 100%;">
                    <el-option label="高" :value="1" />
                    <el-option label="中" :value="2" />
                    <el-option label="低" :value="3" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="scope">
                  <el-button size="small" type="danger" @click="removeOrderItem(scope.$index)">
                    删除
                  </el-button>
            </template>
          </el-table-column>
        </el-table>
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showFormDialog = false">取消</el-button>
        <el-button type="primary" @click="submitOrder" :loading="submitting">确定</el-button>
      </template>
    </el-dialog>

    <!-- 状态更新对话框 -->
    <el-dialog v-model="showStatusDialog" title="更新订单状态" width="400px">
      <el-form label-width="80px">
        <el-form-item label="新状态">
          <el-select v-model="newStatus" placeholder="请选择新状态" style="width: 100%;">
            <el-option label="待排产" value="待排产" />
            <el-option label="已排产" value="已排产" />
            <el-option label="生产中" value="生产中" />
            <el-option label="生产完成" value="生产完成" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showStatusDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmStatusUpdate" :loading="updatingStatus">确定</el-button>
          </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import axios from 'axios';

const API_BASE_URL = 'http://117.72.45.141:8091';

// 响应式数据
const orders = ref([]);
const loading = ref(false);
const submitting = ref(false);
const updatingStatus = ref(false);
const refreshingProgress = ref(false);

const showDetailDialog = ref(false);
const showFormDialog = ref(false);
const showStatusDialog = ref(false);

const currentOrder = ref(null);
const orderFormRef = ref(null);
const isEditing = ref(false);
const formTitle = ref('新增订单');
const newStatus = ref('');

// 搜索表单
const searchForm = reactive({
  customerName: '',
  status: '',
  startDate: '',
  endDate: ''
});

// 分页信息
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
});

// 订单表单
const orderForm = reactive({
  orderId: '',
  customerId: '',
  customerName: '',
      customerContact: '',
    dueDate: '',
    status: '待排产',
    orderItems: []
});

// 表单验证规则
const orderRules = {
  customerName: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  customerContact: [
    { required: true, message: '请输入客户联系方式', trigger: 'blur' }
  ],
  dueDate: [
    { required: true, message: '请选择交货日期', trigger: 'change' }
  ]
};

// 加载订单列表
const loadOrders = async () => {
  loading.value = true;
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchForm
    };
    
    const response = await axios.get(`${API_BASE_URL}/api/orders`, {
      params,
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      const data = response.data.data;
      orders.value = data.records || [];
      pagination.total = data.total || 0;
      pagination.current = data.current || 1;
      pagination.size = data.size || 10;
    } else {
      ElMessage.error(response.data.message || '加载订单列表失败');
    }
  } catch (error) {
    console.error('加载订单列表失败:', error);
    ElMessage.error('加载订单列表失败');
  } finally {
    loading.value = false;
  }
};

// 搜索订单
const searchOrders = () => {
  pagination.current = 1;
  loadOrders();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    customerName: '',
    status: '',
    startDate: '',
    endDate: ''
  });
  searchOrders();
};

// 查看订单详情
const viewOrder = async (order) => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/orders/${order.orderId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      currentOrder.value = response.data.data;
      showDetailDialog.value = true;
    } else {
      ElMessage.error('获取订单详情失败');
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    ElMessage.error('获取订单详情失败');
  }
};

// 新增订单
const addOrder = () => {
  isEditing.value = false;
  formTitle.value = '新增订单';
  Object.assign(orderForm, {
    orderId: '',
    customerId: '',
    customerName: '',
    customerContact: '',
    dueDate: '',
    status: '待排产',
    orderItems: []
  });
  showFormDialog.value = true;
};

// 编辑订单
const editOrder = async (order) => {
  try {
    const response = await axios.get(`${API_BASE_URL}/api/orders/${order.orderId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      isEditing.value = true;
      formTitle.value = '编辑订单';
      Object.assign(orderForm, response.data.data);
      showFormDialog.value = true;
    } else {
      ElMessage.error('获取订单信息失败');
    }
  } catch (error) {
    console.error('获取订单信息失败:', error);
    ElMessage.error('获取订单信息失败');
  }
};

// 添加订单项
const addOrderItem = () => {
  orderForm.orderItems.push({
    productId: '',
    productName: '',
    productDescription: '',
    quantity: 1,
    priority: 2
  });
};

// 删除订单项
const removeOrderItem = (index) => {
  orderForm.orderItems.splice(index, 1);
};

// 提交订单
const submitOrder = async () => {
  if (!orderFormRef.value) return;
  
  try {
    const valid = await orderFormRef.value.validate();
    if (!valid) return;
  } catch (error) {
    return;
  }
  
  if (orderForm.orderItems.length === 0) {
    ElMessage.warning('请添加至少一个订单项');
    return;
  }
  
  submitting.value = true;
  try {
    const url = isEditing.value 
      ? `${API_BASE_URL}/api/orders/${orderForm.orderId}`
      : `${API_BASE_URL}/api/orders`;
    
    const method = isEditing.value ? 'put' : 'post';
    
    const response = await axios[method](url, orderForm, {
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success(isEditing.value ? '订单更新成功' : '订单创建成功');
      showFormDialog.value = false;
      loadOrders();
    } else {
      ElMessage.error(response.data.message || '操作失败');
    }
  } catch (error) {
    console.error('提交订单失败:', error);
    ElMessage.error('操作失败');
  } finally {
    submitting.value = false;
  }
};

// 更新订单状态
const updateOrderStatus = (order) => {
  currentOrder.value = order;
  newStatus.value = order.status;
  showStatusDialog.value = true;
};

// 确认状态更新
const confirmStatusUpdate = async () => {
  if (!newStatus.value) {
    ElMessage.warning('请选择新状态');
    return;
  }
  
  updatingStatus.value = true;
  try {
    const response = await axios.put(
      `${API_BASE_URL}/api/orders/${currentOrder.value.orderId}/status`,
      null,
      {
        params: { status: newStatus.value },
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    }
    );
    
    if (response.data.code === 200) {
      ElMessage.success('订单状态更新成功');
      showStatusDialog.value = false;
      loadOrders();
  } else {
      ElMessage.error(response.data.message || '状态更新失败');
    }
  } catch (error) {
    console.error('状态更新失败:', error);
    ElMessage.error('状态更新失败');
  } finally {
    updatingStatus.value = false;
  }
};

// 删除订单
const deleteOrder = async (order) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除订单 "${order.orderId}" 吗？此操作不可逆。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    const response = await axios.delete(`${API_BASE_URL}/api/orders/${order.orderId}`, {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    });
    
    if (response.data.code === 200) {
      ElMessage.success('订单删除成功');
      loadOrders();
    } else {
      ElMessage.error(response.data.message || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除订单失败:', error);
      ElMessage.error('删除失败');
    }
  }
};

// 刷新订单进度
const refreshOrderProgress = async () => {
  if (!currentOrder.value) return;
  
  refreshingProgress.value = true;
  try {
    const response = await axios.put(
      `${API_BASE_URL}/api/orders/${currentOrder.value.orderId}/refresh`,
      null,
      {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      }
    );
    
    if (response.data.code === 200) {
      ElMessage.success('订单进度刷新成功');
      // 重新获取订单详情
      await viewOrder(currentOrder.value);
    } else {
      ElMessage.error(response.data.message || '刷新失败');
    }
  } catch (error) {
    console.error('刷新订单进度失败:', error);
    ElMessage.error('刷新失败');
  } finally {
    refreshingProgress.value = false;
  }
};

// 分页处理
const handleSizeChange = (val) => {
  pagination.size = val;
  pagination.current = 1;
  loadOrders();
};

const handleCurrentChange = (val) => {
  pagination.current = val;
  loadOrders();
};

// 状态标签类型
const getOrderStatusTagType = (status) => {
  const types = {
    '待排产': 'info',      // 灰色
    '已排产': 'primary',   // 蓝色
    '生产中': 'danger',    // 红色
    '生产完成': 'success'  // 绿色
  };
  return types[status] || 'default';
};

const getItemStatusTagType = (status) => {
  const types = {
    '待排产': 'info',      // 灰色
    '已排产': 'primary',   // 蓝色
    '生产中': 'danger',    // 红色
    '生产完成': 'success'  // 绿色
  };
  return types[status] || 'default';
};

const getPriorityTagType = (priority) => {
  const types = { 1: 'danger', 2: 'warning', 3: 'info' };
  return types[priority] || 'default';
};

const getPriorityLabel = (priority) => {
  const labels = { 1: '高', 2: '中', 3: '低' };
  return labels[priority] || '未知';
};

onMounted(() => {
  loadOrders();
});
</script>

<style scoped>
.order-management {
  padding: 20px;
}

.search-card, .table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

h3 {
  margin: 20px 0 10px 0;
  color: #409eff;
  font-weight: 600;
}
</style>